<?php
class SocketClient {
    public $ip      = '127.0.0.1';
    public $port    = '6666';
    public $sock    = null;

    /**
     * 创建链接
     * @return null 
     */
    public function create($clientId = false, $clientTag = false){
        $this->sock     = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        socket_connect($this->sock, $this->ip, $this->port);

        //发送标示
        if($clientId || $clientTag)
        	$this->signup($clientId, $clientTag);
    }

    /**
     * 注册客户端
     * @return null 
     */
    private function signup($clientId, $clientTag){
        $signInfo   = array(
            'function'  => 'signup',
            'client_id' => $clientId,
            'client_tag'    => $clientTag
        );
        $signInfo   = json_encode($signInfo);
        socket_write($this->sock, $signInfo, strlen($signInfo));
    }

    /**
     * 发送服务端指令
     * @param  array $directive 指令信息
     * @return null            
     */
    public function execute($directive){
        $directive  = json_encode($directive);
        echo "execute directive:".$directive."\n";
        socket_write($this->sock, $directive, strlen($directive));
    }

    /**
     * 监听服务端信息
     * @return null 
     */
    public function listen(){
    	while($receive = socket_read($this->sock, 2048)){
            echo "receive message:".$receive."\n";
        }
    }

    /**
     * 断开连接
     * @return null 
     */
    public function close(){
        socket_close($this->sock);
    }
}

//php SocketClientTest.php id tag
$socket     = new SocketClient();
$socket->create($argv[1], $argv[2]);

//发送指令
$directive  = array(
    'function'  => 'send_info_by_id',
    'client_id'	=> '0001',
    'message'	=> 'send to id 0001!'
);
$socket->execute($directive);
$socket->listen();
$socket->close();